package net.bitacademy.java22.boundary;

import java.io.IOException;

import net.bitacademy.java22.domain.AccessTokenDAO;
import net.bitacademy.java22.domain.AccessTokenVO;
import net.bitacademy.java22.service.GoogleCalendarAdapter;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class PascalWebViewClient extends WebViewClient {
	String code;
	Context context = null;
	
	public PascalWebViewClient(Context context) {
		super();
		this.context = context;
	}

	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {
		Log.d("Song shouldOverrideUrlLoading url", url);
		if(Uri.parse(url).getHost().equals("localhost")){		
			view.loadUrl("file:///android_asset/www/login.html");
			return true;
		}		
		view.loadUrl(url);
		return true;
	}

	@Override
	public void onPageFinished(WebView view, String url) {
		super.onPageFinished(view, url);
		Log.d("Song onPageFinished url", url);
		AccessTokenDAO accessTokenDAO = new AccessTokenDAO(context);
		AccessTokenVO atvo = AccessTokenVO.getInstance();
		if(url.indexOf("code=")!=-1)
		{
			code = url.substring(url.indexOf("code=")+5);
			Log.d("Song onPageFinished code", code);
			GoogleCalendarAdapter instance =  GoogleCalendarAdapter.getInstance();
			instance.setCode(code);
			try {
				instance.setToken();
				accessTokenDAO.insert(atvo);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}	
}